package cn.zyq.demo.system.utils;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云客户端
 */

public class AliOSSClientUtil {

    /** 日志 */
    public static Logger logger = LoggerFactory.getLogger(AliOSSClientUtil.class);

    /** 阿里云API的密钥Access Key ID */
    public static String accessKeyId ="LTAI5tARTSPqK4bDzVNr1jGx";
    /** 阿里云API的密钥Access Key Secret */
    public static String accessKeySecret="4n4SYBfaGLjiFg51EwHVnwm60y3JTH";
    /** 阿里云API的内或外网域名 */
    public static String endpoint="https://oss-cn-chengdu.aliyuncs.com/";
   public static String bucketName="ykb2019";

    /** 阿里云短信签名名称 *//*
    private static String signName = "*****";
    *//** 阿里云短信模板代码 *//*
    private static String templateCode = "*****";
    @Value("{ali.folder}")
    private String folder;*/
    /**
     * 获取阿里云OSS客户端对象
     *
     * @return ossClient
     */
    public static  OSSClient getOSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 创建存储空间
     *
     * @param ossClient OSS连接
     * @param bucketName 存储空间
     * @return
     */
    public static String createBucketName(OSSClient ossClient, String bucketName) {
        // 存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            logger.info("创建存储空间成功");
            return bucket.getName();
        }
        return bucketNames;
    }

    /**
     * 删除存储空间buckName
     *
     * @param ossClient oss对象
     * @param bucketName 存储空间
     */
    public static void deleteBucket(OSSClient ossClient, String bucketName) {
        ossClient.deleteBucket(bucketName);
        logger.info("删除" + bucketName + "Bucket成功");
    }

    /**
     * 根据key删除OSS服务器上的文件
     *
     * @param ossClient oss连接
     * @param bucketName 存储空间
     * @param folder 模拟文件夹名
     * @param key Bucket下的文件的路径名+文件名 如："upload/cake.jpg"
     */
    public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key) {
        ossClient.deleteObject(bucketName, folder + key);
        logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");
    }

    /**
     * 创建模拟文件夹
     *
     * @param ossClient oss连接
     * @param bucketName 存储空间
     * @param folder 模拟文件夹名如
     * @return 文件夹名
     */
    public static   String createFolder(OSSClient ossClient, String bucketName, String folder) {
        // 文件夹名
        final String keySuffixWithSlash = folder;
        // 判断文件夹是否存在，不存在则创建
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 创建文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            logger.info("创建文件夹成功");
            // 得到文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            return fileDir;
        }
        return keySuffixWithSlash;
    }


    /**
     * 上传图片至OSS
     *
     * @param ossClient oss连接
     * @param file 上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @param bucketName 存储空间
     * @param folder 模拟文件夹名
     * @return String 返回文件url
     */
    public static   String upload(OSSClient ossClient, File file, String bucketName, String folder) {
        String resultStr = null;
        try {
            InputStream is = new FileInputStream(file);
            String fileName = file.getName();
            ossClient.putObject(bucketName, folder + fileName, is);
            resultStr = "http://"+endpoint+"/"+folder+fileName;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    /**
     * 上传图片至OSS
     *
     * @param
     *
     *
     * @return String 返回文件url
     */
    public static   String uploadVideo(MultipartFile file) {
        //上传地址
        String uploadUrl=null;
        System.out.println(bucketName+endpoint+accessKeyId+accessKeySecret);
        try {
            //创建实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            System.out.println("ossClient"+ossClient);
            System.out.println("oss:"+ossClient);
            //判断bucketName是否存在
            if(!ossClient.doesBucketExist(bucketName)){
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置bucket属性
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取上传的文件流
            InputStream inputStream=file.getInputStream();
            //构建日期的文件夹路径 avatar/2021/9/12/文件名
            String datePath= new DateTime().toString("yyy/MM/dd");
            //获取上传文件的全名称
            String original = file.getOriginalFilename();
            //获取uuid 随机生成的,每次都不同 9c649622-7b7b-4fca-ba74-daae5ea4b3c8 变为9c6496227b7b4fcaba74daae5ea4b3c8
            String fileName = UUID.randomUUID().toString().replace("-", "");
            //获取文件路径的扩展名 meizi.jpg  就应该是jpg
            String fileType = original.substring(original.lastIndexOf("."));
            //并接文件名称 9c6496227b7b4fcaba74daae5ea4b3c8.jpg
            String newName=fileName+fileType;
            //生成文件夹   avatar/2021/9/12/9c6496227b7b4fcaba74daae5ea4b3c8.jpg
            fileName= datePath+"/"+newName;
            //每次上传的文字都是不能相同的---uuid方法 文件格式：yyyy/MM/dd+uuid

            //要实现图片预览效果，还需要设置
            //1.设置文件的ACL(权限)，要么是公共读，要么是公共读写
            //2.一定要设置文本类型(image/jpg)
            ObjectMetadata objectMetadata=new ObjectMetadata();
            //设置公共读权限
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getContentType(fileType));
            ossClient.putObject(bucketName, fileName, file.getInputStream(),objectMetadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            //默认十年不过期
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            //获取在线访问的url bucket名称  文件名   过期时间
            uploadUrl = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();

        }catch (Exception e){
            e.printStackTrace();
        }
        //返回数据是关键如果你直接返回uploadUrl那么后面就会出现很多参数，所以要进行截取
        System.out.println(uploadUrl);
        return uploadUrl.substring(0,uploadUrl.indexOf("?"));
    }


    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        // 文件的后缀名
        String FilenameExtension = fileName.substring(fileName.lastIndexOf("."));
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx"))
        {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp4")) {//MP4格式
            return "video/mp4";
        }
        return "image/jpg";

    }


    /*
    *//**
     * 阿里云短信验证码
     * @return
     *//*
    public static String smsCode(String phone){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        String smsCode = RandomUtil.randomNumbers(6);
        request.setSysMethod(MethodType.POST);
        request.setSysVersion("2017-05-25");
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam","{code:"+smsCode+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return smsCode;
    }*/
}
